import Vue from "vue"
export const URL = {
	API: 'https://api.gyy988.cn/',
	IMG: '',
}

export const request = ({url, data, method, header={}, loading=true, errorToast=true, success, fail, complete}) => {
	return new Promise((resolve, reject)=>{
		loading && uni.showLoading({ title: '加载中...', mask: true})
		let token = uni.getStorageSync('TOKEN_VALUE')
		if(token){
			header.Authorization = token
		}
		uni.request({
		    url: URL.API + url,
		    data: data,
		    method: method||"POST",
		    header,
			success: (res) => {
				success && success(res.data)
			},
			fail: (err) => {
				fail && fail(err.data||err)
			},
		    complete: com => {
				loading && uni.hideLoading();
				// 定义失败话语
				let errorMesage = '网络错误，请稍后重试';
				if(com && com.data){
					errorMesage = com.data.message || com.data.error || com.data
				}
				// 请求成功失败的promise回调
				if (com && com.data && com.data.success){
					// 成功
					resolve(com.data)
				} else {
					reject(errorMesage);
					
					// 显示错误弹窗、并且全局还未出现过弹窗，防止一次性请求多个接口报错出现多次弹窗的情况
					if(errorToast && !Vue._requestErrorModel){
						uni.showModal({
							title: '温馨提示',
							content: errorMesage,
							showCancel: false,
							success: () => {
								Vue._requestErrorModel = false;
							}
						})
						Vue._requestErrorModel = true
					}
					
				}
				complete && complete(com.data || com);
			}
		})
	})
}

// 防抖
export const debounce = (fn, delay=500)=>{
	if(Vue.prototype.__debounce_timer__){
		clearTimeout(Vue.prototype.__debounce_timer__);
		Vue.prototype.__debounce_timer__ = null
	}
	Vue.prototype.__debounce_timer__ = setTimeout(()=> {
		fn.apply(this, arguments);
	}, delay)
}

